package com.cwnu.controller;

import com.cwnu.entity.Result;
import com.cwnu.entity.User;
import com.cwnu.service.UserService;
import com.cwnu.utils.JwtUtil;
import com.cwnu.utils.ThreadLocalUtil;
import com.cwnu.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 用户注册
    @PostMapping("/register")
    public Result register(String username, String password, Integer age, String school) {
        // 先查找用户是否存在
        User user = userService.findByUserName(username);

        if (user == null) {
            // 没有找到该用户，执行注册
            userService.register(username, password, age, school);
            return Result.success();
        } else {
            // 找到了该用户，不执行注册
            return Result.error("该用户已经注册，请更换用户名重新注册");
        }
    }


    // 用户登录
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, Object> params) {
        String username = (String) params.get("username");
        String password = (String) params.get("password");
        // 先查询用户是否存在
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户名不存在，请重试");
        }
        // 判断密码是否正确
        if (password.equals(loginUser.getPassword())) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 登录之后，向redis中注入新的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.DAYS);
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }

    // 获取用户基本信息（不获取密码）
    @GetMapping("/userInfo")
    public Result getUserInfo() {
        Map<String, Object> mp = ThreadLocalUtil.get();
        String username = (String) mp.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    // 更新用户数据
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user, @RequestHeader("Authorization") String oldToken) {
        userService.update(user);
        return Result.success();
    }

    // 更新用户密码
    @PutMapping("/updatePwd")
    public Result updatePassWord(@RequestBody Map<String, String> mp, @RequestHeader("Authorization") String token) {
        // 1、参数校验
        String oldPassWord = mp.get("old_pwd");
        String newPassWord = mp.get("new_pwd");
        String repeatPassWord = mp.get("re_pwd");

        // 参数是否为空
        if (!StringUtils.hasLength(oldPassWord) || !StringUtils.hasLength(newPassWord) || !StringUtils.hasLength(repeatPassWord)) {
            return Result.error("参数不完整");
        }

        // 检查原密码是否正确
        Map<String, String> map = ThreadLocalUtil.get();
        String username = map.get("username");
        User loginUser = userService.findByUserName(username);
        String password = loginUser.getPassword();
        if (!password.equals(oldPassWord)) {
            return Result.error("原密码不正确");
        }

        // 检查新密码和确认密码是否一致
        if (!newPassWord.equals(repeatPassWord)) {
            return Result.error("两次密码不一致");
        }

        // 检查新旧密码是否一致
        if (oldPassWord.equals(newPassWord)) {
            return Result.error("新旧密码不能一致");
        }

        // 更新密码
        userService.updatePassWord(newPassWord);

        // 用户更新密码成功，把原密码对应的token从redis中删除
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    // 注销用户
    @DeleteMapping("/deleteUser")
    public Result logOut(@RequestHeader("Authorization") String token) {
        userService.logOut();
        // 用户已注销，将用户信息从redis中删除
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
